<!--
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-08-05 14:06:13
-->
<template>
  <!-- 搜索时显示 -->
  <div v-show="!isShow">
    <form action="/">
      <van-search
        ref="searchRef"
        v-model="content"
        show-action
        :placeholder="defaultKeyword?.keyword"
        @search="onSearch"
        @cancel="onCancel"
        @update:model-value="onChange"
      />
    </form>
    <div class="hot" v-if="!isShowCell">
      <div style="margin-bottom: 20px" v-if="hosList.length">
        <p>
          历史记录<span style="float: right"
            ><van-icon name="delete-o" @click="deleteHistory"
          /></span>
        </p>
        <div class="hotButton">
          <van-button
            size="small"
            v-for="(item, index) in hosList"
            :key="index"
            @click="searchClick(item)"
            >{{ item }}</van-button
          >
        </div>
      </div>
      <div>
        <p>热门搜索</p>
        <div class="hotButton">
          <van-button
            :type="index === 0 ? 'danger' : 'default'"
            size="small"
            :plain="index === 0 ? true : false"
            v-for="(item, index) in hotKeywordVOList"
            :key="index"
            @click="searchClick(item.keyword)"
            >{{ item.keyword }}</van-button
          >
        </div>
      </div>
    </div>

    <div v-else>
      <van-cell
        :title="item"
        is-link
        v-for="(item, index) in keywords"
        :key="index"
        @click="searchClick(item)"
      />
    </div>
  </div>

  <!-- 搜索后显示 -->
  <div v-show="isShow">
    <van-sticky>
      <van-search
        v-model="content"
        placeholder="请输入搜索关键词"
        @clear="toSearch"
        @focus="toSearch"
      />

      <!-- 条件标签 -->
      <van-row>
        <van-col
          v-for="(item, index) in ['综合', '价格', '分类']"
          :key="index"
          span="8"
          :class="index === activeIndex ? 'active' : ''"
          @click="changeActiveIndex(index)"
          >{{ item }}</van-col
        >
      </van-row>
    </van-sticky>

    <!-- 商品列表 -->
    <van-list v-model:loading="loading" finished-text="没有更多了" :offset="10" @load="onLoad">
      <div class="goods-list" v-if="!!goodsList">
        <div v-for="item in goodsList" :key="item.id">
          <GoodsCard :item="item"></GoodsCard>
        </div>
        <!-- 数据是否加载完毕 -->
        <div class="finish" v-if="!goodsList">暂无数据~~~</div>
      </div>
    </van-list>
  </div>
</template>

<script lang="ts" setup>
import { reqGetInitData, reqSearchAutoComplete, reqGetGoodsList } from '@/api/search'
import router from '@/router'
import type { IDefaultKeyword } from '@/types/search'
import type { SearchInstance } from 'vant'
import { onMounted } from 'vue'
import { ref, nextTick } from 'vue'

import _ from 'lodash'
// 搜索类型切换
const activeIndex = ref(0)
const changeActiveIndex = (index: number) => {
  activeIndex.value = index
}

const loading = ref(false)

const searchRef = ref<SearchInstance>()
// 搜索和结果切换
const isShow = ref(false)

// #region 搜索出商品逻辑

const goodsList = ref<any[]>([])
const toSearch = () => {
  isShow.value = false
  if (content.value) {
    onChange()
  } else {
    isShowCell.value = false
  }
  // 获取输入框焦点-----------------------------
  nextTick(() => {
    searchRef.value?.focus()
  })
}
// 数据触底继续获取
const onLoad = _.throttle(async () => {
  loading.value = true
  const res = await reqGetGoodsList(content.value)
  goodsList.value = [...goodsList.value, ...(res.data as any).directlyList]

  loading.value = false
}, 500)

//#endregion

// #region 输入关键词搜索的逻辑
// 当输入关键词时显示
const isShowCell = ref(false)
// 搜索关键词
const content = ref('')

// 点击推荐和历史记录
const searchClick = (item: string) => {
  isShow.value = true
  content.value = item
  onSearch()
}

// 搜索
const onSearch = async () => {
  let historyArr = JSON.parse(localStorage.getItem('historyArr') as string) || []

  // 搜索后将关键词在本地存储
  if (!historyArr.includes(content.value)) {
    historyArr.push(content.value)
    hosList.value.push(content.value)
    localStorage.setItem('historyArr', JSON.stringify(historyArr))
  }

  const res = await reqGetGoodsList(content.value)
  goodsList.value = (res.data as any).directlyList

  // console.log(goodsList.value)

  isShow.value = true
}
// 取消按钮
const onCancel = () => {
  router.push('/home')
}

// 用户输入关键词时的数据
const keywords = ref([])

// 输入框内容发生改变时
const onChange = _.debounce(async () => {
  const res = await reqSearchAutoComplete(content.value)
  if (res.code == 200) {
    keywords.value = res.data
    isShowCell.value = true
  }
  if (content.value.length === 0) {
    isShowCell.value = false
  }
}, 300)

// 创建搜索历史数据
const hosList = ref(JSON.parse(localStorage.getItem('historyArr') as string) || [])

//#endregion

// 删除本地搜索历史记录
const deleteHistory = () => {
  hosList.value = []
  localStorage.removeItem('historyArr')
}

// 搜索框数据
const defaultKeyword = ref<IDefaultKeyword>()
const hotKeywordVOList = ref<IDefaultKeyword[]>([])

onMounted(async () => {
  const res = await reqGetInitData()

  if (res.code == 200) {
    defaultKeyword.value = res.data.defaultKeyword
    hotKeywordVOList.value = res.data.hotKeywordVOList
  }
})
</script>

<script lang="ts">
export default {
  name: 'SearchView'
}
</script>

<style lang="less" scoped>
.hot {
  margin: 10px;
  p {
    color: #999999;
    font-size: 21px;
  }
  .hotButton {
    margin-top: 5px;
    ::v-deep(.van-button) {
      margin: 0px 5px;
    }
  }
}
::v-deep(.van-row) {
  line-height: 40px;
  height: 40px;
  text-align: center;
  background-color: #fafafa;
  font-size: 15px;
  border-bottom: 2px solid #eaeaea;
}
.goods-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 10px;
}

.finish {
  height: 80rpx;
  line-height: 80rpx;
  /* display: block !important; */
  overflow: hidden;
  width: 100%;
  text-align: center;
  color: #f3514f;
  border-top: 1rpx solid #ccc;
  font-size: 28rpx;
}

.active {
  color: red;
}
</style>
